import { _decorator, clamp, Component, Node, randomRangeInt } from 'cc';
import { BattleContext } from './BattleContext';
const { ccclass, property } = _decorator;

@ccclass('Camera')
export class Camera extends Component {

    private _isShaking: boolean = false; // 是否在震动中
    private _duration: number = 0.2; // 震动持续时间
    private _shakeLevel: number = 15; // 震动幅度
    private _timer: number = 0; // 震动计时器

    start() {

    }

    update(deltaTime: number) {
        if(!BattleContext.ndPlayer || !BattleContext.ndPlayer.isValid) return;

        if(this._isShaking) {
            this._timer+=deltaTime;
            if(this._timer >= this._duration) {

                this._isShaking = false;
                this._timer = 0;

            } else {
                // 抖动
                let shakeX = randomRangeInt(-this._shakeLevel, this._shakeLevel);
                let shakeY = randomRangeInt(-this._shakeLevel, this._shakeLevel);
                this.node.setWorldPosition(
                    BattleContext.ndPlayer.worldPosition.x + shakeX,
                    BattleContext.ndPlayer.worldPosition.y + shakeY,
                    this.node.worldPosition.z
                )
            }
        } else {
            this.node.worldPosition = BattleContext.ndPlayer.worldPosition; // 设置相机位置
        }

        const x = clamp(this.node.position.x, -654, 654);
        const y = clamp(this.node.position.y, -654, 654);
        this.node.setPosition(x,y);


        
    }

    shake(duration?:number) {
        this._isShaking = true;
        this._timer = 0;
    }
}


